package com.googlecode.mailnet.math.distribution;

import com.googlecode.mailnet.math.RandomUtil;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author Iskander Akishev
 */
class DiscreteDistribution implements Distribution {
    private final Distribution[] distributions;
    private final double[] p;

    DiscreteDistribution(ArrayList<Distribution> distributions, ArrayList<Double> probabilities) {
        if (distributions.size() != probabilities.size()) {
            throw new IllegalArgumentException("parameters must have equal lengths");
        }
        this.distributions = distributions.toArray(new Distribution[distributions.size()]);
        p = new double[probabilities.size() - 1];
        double sum = 0;
        for (int i = 0; i < p.length; i++) {
            double cur = probabilities.get(i);
            if (cur <= 0) {
                throw new IllegalArgumentException("probability is negative (" + cur + ")");
            }
            sum += cur;
            p[i] = sum;
        }
        sum += probabilities.get(p.length);
        for (int i = 0; i < p.length; i++) {
            p[i] /= sum;
        }
    }

    public double getValue() {
        double c = RandomUtil.nextDouble();
        int i = Arrays.binarySearch(p, c);
        if (i < 0) {
            i = -i - 1; 
        }
        return distributions[i].getValue();
    }
}
